package com.qdsg.ysg.doctor.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.ui.dialog.ApplyPermissionDialog;
import com.qdsg.ysg.doctor.ui.dialog.SelectPicModeDialog;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.PermissionsChecker;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UriUtils;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.response.BaseStringResponse;
import com.rest.response.DocInfoVO;
import com.rest.response.PicUploadResponse;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.PackageUtils;
import jz.joyoung.robot.util.PreferencesHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.qdsg.ysg.doctor.ui.AddRegistrationActivity.REQUEST_GALLERY;
import static com.qdsg.ysg.doctor.ui.AddRegistrationActivity.REQUEST_OPEN_CAMERA;

/**
 * Created by Administrator on 2018/6/11.
 */

public class UserInfoActivity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.avatar)
    ImageView ivAvatar;
    @BindView(R.id.rl_avatar)
    RelativeLayout rlAvatar;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.rl_name)
    RelativeLayout rlName;
    @BindView(R.id.rl_introduction)
    RelativeLayout rlIntroduction;
    @BindView(R.id.tv_introduction)
    TextView tvIntroduction;
    @BindView(R.id.rl_goodAt)
    RelativeLayout rlGoodAt;
    @BindView(R.id.tv_goodAt)
    TextView tvGoodAt;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_manufacturer)
    TextView tvManufacturer;
    private SelectPicModeDialog mSelectPicModeDialog = null;
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri, resourceId;
    public ProgressDialog dialog;

    public static final int REQUEST_EDIT_NAME = 0x033;
    public static final int REQUEST_EDIT_INTRODUCTION = 0x044;
    public static final int REQUEST_EDIT_GOODAT = 0x055;
    private String docId, avatarUrl, name, introduction, goodAt;
    // 所需的全部权限
    static final String[] cameraPermissions = new String[]{Manifest.permission.CAMERA};
    String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};//权限数组
    private static final int PERMISSION_REQUEST_CAMERA = 1;
    private static final int PERMISSION_REQUEST_STORAGE = 2;
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        tvTitle.setText( "我的信息" );
        tvVersion.setText( PackageUtils.getVersionName( mContext ) );
        tvManufacturer.setText( Build.MANUFACTURER + " " + Build.MODEL );
        mPermissionsChecker = new PermissionsChecker( mContext );
        if (BaseApplication.isAudit != 0) {
            rlIntroduction.setVisibility( View.GONE );
            tvIntroduction.setVisibility( View.GONE );
            rlGoodAt.setVisibility( View.GONE );
            tvGoodAt.setVisibility( View.GONE );
        }
    }

    @Override
    protected void initData() {
        getUserInfo();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_userinfo;
    }

    private void getUserInfo() {
        RestProxy.getInstance().getUserInfo( new Observer<DocInfoVO>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DocInfoVO DocInfo) {
                try {
                    name = DocInfo.data.name;
                    introduction = DocInfo.data.introduction;
                    goodAt = DocInfo.data.goodAt;
                    tvUsername.setText( DocInfo.data.name );
                    tvIntroduction.setText( DocInfo.data.introduction );
                    tvGoodAt.setText( DocInfo.data.goodAtInfo );
                    docId = DocInfo.data.docId;
                    avatarUrl = DocInfo.data.avatarUrl;
                    if (!UtilString.isEmpty( avatarUrl )) {
                        Log.d("__head-get",""+avatarUrl);
                        ImageLoaderHelper.getInstance().GlideCircleImageLoader( mContext, avatarUrl, ivAvatar );
                    } else {
                        if ("女".equals( BaseApplication.sex )) {
                            ivAvatar.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_girl ) );
                        } else {
                            ivAvatar.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_boy ) );
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    @OnClick({R.id.rl_avatar, R.id.rl_name, R.id.rl_introduction, R.id.rl_goodAt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_avatar:
                // 缺少权限时, 进入权限配置页面
                checkPermission();
                break;
            case R.id.rl_name:
                Intent intent = new Intent( mContext, UserInfoEditActivity.class );
                intent.putExtra( "editType", "name" );
                intent.putExtra( "editData", name );
                startActivityForResult( intent, REQUEST_EDIT_NAME );
                break;
            case R.id.rl_introduction:
                Intent intentOne = new Intent( mContext, UserInfoEditActivity.class );
                intentOne.putExtra( "editType", "introduction" );
                intentOne.putExtra( "editData", introduction );
                startActivityForResult( intentOne, REQUEST_EDIT_INTRODUCTION );
                break;
            case R.id.rl_goodAt:
                Intent intentTwo = new Intent( mContext, DoctorGoodAtEditActivity.class );
                intentTwo.putExtra( "goodAtCode", goodAt );
                startActivityForResult( intentTwo, REQUEST_EDIT_GOODAT );
                break;
            default:
                break;
        }
    }


    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener( new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {

                    Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile( oriPhotoFile );
                    } else {
                        assert oriPhotoFile != null;
                        imgUriOri = FileProvider.getUriForFile( mContext, UIConstants.FILE_PROVIDER_URI, oriPhotoFile );
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra( MediaStore.EXTRA_OUTPUT, imgUriOri );
                    intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
                    startActivityForResult( intent, REQUEST_OPEN_CAMERA );

                }

                @Override
                public void pickFromAlbumClick() {
                    @SuppressLint("IntentReset") Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI );
                    intent.setType( "image/*" );
                    startActivityForResult( intent, REQUEST_GALLERY );
                }
            } );
        }
        mSelectPicModeDialog.show( getSupportFragmentManager(), "SelectPicModeDialog" );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                getPresignedUrl( imgPathOri );
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri( this, imgUriSel );
                    getPresignedUrl( imgPathSel );
                }
                break;
            case REQUEST_EDIT_NAME:
                tvUsername.setText( data.getStringExtra( "editData" ) );
                break;
            case REQUEST_EDIT_INTRODUCTION:
                tvIntroduction.setText( data.getStringExtra( "editData" ) );
                break;
            case REQUEST_EDIT_GOODAT:
                Log.e( "REQUEST_EDIT_GOODAT---", Objects.requireNonNull( data.getStringExtra( "editData" ) ) );
                getUserInfo();
                break;
            default:
                break;
        }
    }

    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPathSel) {
        showProgressDialog( this );
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        RestProxy.getInstance().getPresignedUrl( "3", new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseStringResponse baseStringResponse) {
                try {
                    String data = baseStringResponse.data;
                    if (data.contains( "?" )) {
                        String substring = data.substring( 0, data.indexOf( "?" ) );
                        resourceId = substring.substring( substring.lastIndexOf( "/" ) + 1 );
                        Log.e( "presignedUrl -----", resourceId );
                        uploadFileMinio( imgPathSel,data );
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {
            }
        } );
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private void uploadFileMinio(String imgPath,String url) {
        new Thread( () -> {
            try {
                Log.e( "TAG-路径-----", imgPath );
                File file = new File( imgPath );
                FileInputStream fileInputStream = new FileInputStream( file );
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e( "字节数---", available + "" );
                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse( "image/png" );//设置类型
                RequestBody requestBody = RequestBody.create( mediaType, file );//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url( url)
                        .put( requestBody )
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall( request );
                call.enqueue( new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.e( "TAG-失败：", e.toString() + "" );
                        dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        assert response.body() != null;
                        String string = response.body().toString();
                        Log.e( "minio成功---", string + "" );
                        uploadFileTb( imgPath, available + "" );
                    }
                } );

            } catch (Exception e) {
                e.printStackTrace();
            }
        } ).start();


    }

    /**
     * 上传照片到服务器数据库
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        RestProxy.getInstance().uploadFileTb( "3", "30", resourceId, BaseApplication.doctorId, available, "0", new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread( () -> {
                        dismissProgressDialog();
                        Log.e( "头像---", picUploadResponse.data.shareUrl );
                        if (!UtilString.isEmpty( picUploadResponse.data.shareUrl )) {
                            BaseApplication.avatar = picUploadResponse.data.shareUrl;
                            Log.d("__head-set",""+picUploadResponse.data.shareUrl);
                            ImageLoaderHelper.getInstance().GlideCircleImageLoader( mContext, picUploadResponse.data.shareUrl, ivAvatar );
                        }
                    } );

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.onError( mContext, e );
            }

            @Override
            public void onComplete() {
            }
        } );
    }


    /**
     * 创建原图像保存的文件
     */
    protected File createOriImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat") String imgNameOri = "HomePic_" + new SimpleDateFormat( "yyyyMMdd_HHmmss" ).format( new Date() );
        File pictureDirOri = new File( Objects.requireNonNull( getExternalFilesDir( Environment.DIRECTORY_PICTURES ) ).getAbsolutePath() + "/OriPicture" );
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    @SuppressLint("CheckResult")
    private void checkPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance( "3", true );
        applyPermissionDialog.show( getSupportFragmentManager(), "applyPermissionDialog" );
        applyPermissionDialog.setmListener( new ApplyPermissionDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                boolean agreeCamera = PreferencesHelper.getInstance().getBoolean( mContext, "agreeCamera" );
                if (!agreeCamera) {
                    ActivityCompat.requestPermissions( mContext, PERMISSIONS, PERMISSION_REQUEST_CAMERA );
                } else {
                    showSelectHeadPicDialog();
                }
            }

            @Override
            public void onCancel() {

            }
        } );

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        if (requestCode != PERMISSION_REQUEST_CAMERA) {
            super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        } else {
            LogUtil.e( "权限回调--" + Arrays.toString( permissions ) );
            PreferencesHelper.getInstance().set( mContext, "agreeCamera", true );
            showSelectHeadPicDialog();
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//                // Permission Granted 授予权限
//                //处理授权之后逻辑
//
//
//            } else {
//                // Permission Denied 权限被拒绝
//                ToastUtil.showToast( mContext, "请同意相册和存储权限，否则功能无法使用" );
//                startNotificationSetting(mContext);
//            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        // TODO: add setContentView(...) invocation
        ButterKnife.bind( this );
    }
}
